//
//  ViewController.swift
//  whack-a-mole
//
//  Created by wxc on 2019/9/19.
//  Copyright © 2019 wxc. All rights reserved.
//

/*
目录结构
        - ViewController
        - SettingController
        - GoalAndTimerViewController
        - MouseItemView
        - SoundTool
        -

 bug 游戏中切换reps 顺序。来个当前reps
     重新开始reps不重置
 
 */

import UIKit
import AVFoundation

var ScreenWidth  = UIScreen.main.bounds.size.width
var ScreenHeight = UIScreen.main.bounds.size.height
var Y_MouseItem = ScreenHeight/2 - (ScreenWidth - 40)/6
var W_MouseItem = (ScreenWidth - 40)/3

let NotifictionKey_Sound_Pause = "Name_NotifictionKey_Sound_Pause"
let NotifictionKey_Sound_Play = "Name_NotifictionKey_Sound_Play"

let GoalKey = "GoalKey_only_" // reps key
let TimeKey = "TimeKey_only_"

let GamingRepsKey = "GamingRepsKey_only_" // 游戏中进入改变reps顺序时 ，记录当前reps

let ShowRepsKey = "ShowRepsKey_only_"
let ShowRepsGoalKey = "ShowRepsGoalKey_only_"
let ShowRepsUpAndDownKey = "ShowRepsUpAndDownKey_only_"

let ShowTimerKey = "ShowTimerKey_only_"
let ShowTimerGoalKey = "ShowTimerGoalKey_only_"
let ShowTimerUpAndDownKey = "ShowTimerUpAndDownKey_only_"

let SoundIsPlayKey = "SoundIsPlayKey_only_"

class ViewController: UIViewController,MouseItemViewDelegate {
    
    var _tempMouseIndex : NSInteger = 0
    let level : NSInteger           = 0
    var hitMouseCount : NSInteger   = 0 // 地鼠个数
    var TimerNum : NSInteger        = 0 // 计时器调用次数
    var ArmBool : Bool              = false
    var TriggerBool : Bool          = false
    var myTimer = Timer.init()
    var itemsArray : NSMutableArray = NSMutableArray.init(capacity: 1)
    let codeTimer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
    var hour = 0
    var min = 0
    var sec = 0
    var hitSound : SoundTool = SoundTool()

    // MARK: - lazy
    private lazy var bg_imgV : UIImageView = {
        let bg_imgV = UIImageView.init()
        bg_imgV.image = UIImage.init(named: "背景图")
        bg_imgV.contentMode = .scaleAspectFill
        bg_imgV.frame = CGRect.init(x: 50, y: Y_MouseItem, width: ScreenWidth-100, height: 300)
        return bg_imgV
    }()// 背景图
    
    private lazy var currentScore_lab : UILabel = {
        let currentScore_lab = UILabel.init()
        currentScore_lab.textColor = UIColor.red
        currentScore_lab.text = "Reps:0"
        currentScore_lab.font = UIFont.systemFont(ofSize: UIFont.labelFontSize)
        currentScore_lab.frame = CGRect.init(x: 10, y: 80, width: 200, height: 30)
        return currentScore_lab
    }()// 当前分数
    
    private lazy var time_lab : UILabel = {
        let time_lab = UILabel.init()
        time_lab.textColor = UIColor.red
        time_lab.text = "Time:00:00:00"
        time_lab.font = UIFont.systemFont(ofSize: UIFont.labelFontSize)
        time_lab.frame = CGRect.init(x: 10, y: 50, width: 200, height: 30)
        return time_lab
    }()// 当前时间
    
    private lazy var goal_Reps_lab : UILabel = {
        let goal_Reps_lab = UILabel.init()
        goal_Reps_lab.textColor = UIColor.red
        goal_Reps_lab.text = "Goal Reps"
        goal_Reps_lab.font = UIFont.systemFont(ofSize: UIFont.labelFontSize)
        goal_Reps_lab.frame = CGRect.init(x: 200, y: 80, width: 100, height: 30)
        return goal_Reps_lab
    }()// 目标分数
    
    private lazy var goal_Time_lab : UILabel = {
        let goal_Time_lab = UILabel.init()
        goal_Time_lab.textColor = UIColor.red
        goal_Time_lab.text = "Goal Time:"
        goal_Time_lab.font = UIFont.systemFont(ofSize: UIFont.labelFontSize)
        goal_Time_lab.frame = CGRect.init(x: 200, y: 50, width: 200, height: 30)
        return goal_Time_lab
    }()// 目标时间

    private lazy var setting_btn : UIButton = {
        let setting_btn = UIButton.init()
        setting_btn.setTitle("Setting", for: .normal)
        setting_btn.setTitleColor(.blue, for: .normal)
        setting_btn.titleLabel?.font = UIFont.systemFont(ofSize: UIFont.labelFontSize)
        setting_btn.addTarget(self, action: #selector(settingClick), for: .touchUpInside)
        setting_btn.frame = CGRect.init(x: ScreenWidth - 100, y: 50, width: 80, height: 40)
        return setting_btn
    }()// 设置 按钮
    
    private lazy var goal_Timer_btn : UIButton = {
        let goal_Timer_btn = UIButton.init()
        goal_Timer_btn.setTitle("Goal", for: .normal)
        goal_Timer_btn.setTitleColor(.blue, for: .normal)
        goal_Timer_btn.titleLabel?.font = UIFont.systemFont(ofSize: UIFont.labelFontSize)
        goal_Timer_btn.addTarget(self, action: #selector(goalTimerClick), for: .touchUpInside)
        goal_Timer_btn.frame = CGRect.init(x: ScreenWidth - 100, y: 80, width: 80, height: 40)
        return goal_Timer_btn
    }()// Goal and Timer
    
    private lazy var arm_btn : UIButton = {
       let arm_btn = UIButton.init()
        arm_btn.backgroundColor = UIColor.lightGray
        arm_btn.setTitle("ARM", for: .normal)
        arm_btn.layer.borderWidth = 1
        arm_btn.titleLabel?.font = UIFont.systemFont(ofSize: UIFont.labelFontSize)
        arm_btn.layer.borderColor = UIColor.black.cgColor
        arm_btn.setTitleColor(UIColor.black, for: .normal)
        arm_btn.addTarget(self, action: #selector(armAndTriggerBtnClick(sender:)), for: .touchUpInside);
        arm_btn.frame = CGRect.init(x: 10, y: Y_MouseItem, width: 80, height: 30);
        return arm_btn
    }()// arm 按钮
    
    private lazy var trigger_btn : UIButton = {
        let trigger_btn = UIButton.init()
        trigger_btn.backgroundColor = UIColor.lightGray
        trigger_btn.setTitle("TRIGGER", for: .normal)
        trigger_btn.layer.borderWidth = 1
        trigger_btn.titleLabel?.font = UIFont.systemFont(ofSize: UIFont.labelFontSize)
        trigger_btn.layer.borderColor = UIColor.black.cgColor
        trigger_btn.setTitleColor(UIColor.black, for: .normal)
        trigger_btn.addTarget(self, action: #selector(armAndTriggerBtnClick(sender:)), for: .touchUpInside);
        trigger_btn.frame = CGRect.init(x: ScreenWidth - 10 - 80, y: Y_MouseItem, width: 80, height: 30);
        return trigger_btn
    }()// trigger 按钮
    
    private lazy var arm_imgV : UIImageView = {
        let arm_imgV = UIImageView.init()
        arm_imgV.contentMode = .scaleToFill
        arm_imgV.image = UIImage.init(named: "chuizi2")
        arm_imgV.frame = CGRect.init(x: itemView.zc_x, y: itemView.zc_y - 64, width: 128, height: 128)
        return arm_imgV
    }()// arm 锤子
    
    private lazy var trigger_imgV : UIImageView = {
        let trigger_imgV = UIImageView.init()
        trigger_imgV.contentMode = .scaleToFill
        trigger_imgV.image = UIImage.init(named: "chuizi")
        trigger_imgV.frame = CGRect.init(x: itemView2.zc_x + itemView2.zc_width - 128, y: itemView2.zc_y-64, width: 128, height: 128)
        return trigger_imgV
    }()// trigger 锤子
    
    private lazy var itemView : MouseItemView = {
        let itemView = MouseItemView.init(frame: CGRect.init(x: ScreenWidth/2 - W_MouseItem - 10, y: Y_MouseItem, width: W_MouseItem, height: W_MouseItem))
        itemView.delegate = self
        itemView.backgroundColor = UIColor.clear
        return itemView
    }()// arm 地鼠
    
    private lazy var itemView2 : MouseItemView = {
        let itemView2 = MouseItemView.init(frame: CGRect.init(x: ScreenWidth/2 + 10, y: Y_MouseItem, width: W_MouseItem, height: W_MouseItem))
        itemView2.delegate = self
        itemView2.backgroundColor = UIColor.clear
        return itemView2
    }()// trigger 地鼠

    private lazy var start_btn : UIButton = {
        let start_btn = UIButton.init()
        start_btn.setTitle("Start", for: .normal)
        start_btn.setTitleColor(.red, for: .normal)
        start_btn.backgroundColor = UIColor.lightGray
        start_btn.titleLabel?.font = UIFont.systemFont(ofSize: UIFont.labelFontSize)
        start_btn.addTarget(self, action: #selector(startClick(sender:)), for: .touchUpInside)
        start_btn.frame = CGRect.init(x: ScreenWidth/2 - 100, y: ScreenHeight - 100, width: 200, height: 50)
        return start_btn
    }()// 开始游戏 按钮
    
    // MARK: - viewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        playBackgroundMusic()
        if UserDefaults.standard.object(forKey: SoundIsPlayKey) != nil
        {
            if "\(UserDefaults.standard.object(forKey: SoundIsPlayKey) ?? "")" == "true" {
                setupSound_On()
            }
            else
            {
                setupSound_Off()
            }
        }
        
        if (UserDefaults.standard.object(forKey: "speed") != nil){}
        else
        {
            UserDefaults.standard.set(1, forKey: "speed")
            UserDefaults.standard.synchronize()
        }
        if (UserDefaults.standard.object(forKey: GoalKey) != nil) {}
        else
        {
            UserDefaults.standard.set(10, forKey: GoalKey)
            UserDefaults.standard.synchronize()
        }
        if (UserDefaults.standard.object(forKey: TimeKey) != nil){}
        else
        {
            UserDefaults.standard.set(20, forKey: TimeKey)
            UserDefaults.standard.synchronize()
        }

    }
    
    func playBackgroundMusic() -> Void {
        let pathString = Bundle.main.path(forResource: "背景音乐bg", ofType: "wav")
        let url = URL.init(fileURLWithPath: pathString!)
        self.hitSound.circulating = true
        self.hitSound.playSoundWithURL(soundURL: url)
    }

    func hitMouse(mouseItem: MouseItemView?) {
        print(self.ArmBool,self.TriggerBool)

        if _tempMouseIndex == 1
        {
            mouseItem!.TaphitMouseSound(name: "First_Tone")
            self.ArmBool = true ; return ;
        }
        if _tempMouseIndex == 0
        {
            mouseItem!.TaphitMouseSound(name: "Second_Tone")

            if self.ArmBool == true
            {
                self.TriggerBool = true
                if self.ArmBool == true && self.TriggerBool == true
                {                    
                    if UserDefaults.standard.object(forKey: ShowRepsUpAndDownKey) != nil
                    {
                        if "\(UserDefaults.standard.object(forKey: ShowRepsUpAndDownKey) ?? "")" == "up"
                        {
                            self.hitMouseCount = self.hitMouseCount + 1
                        }
                        else
                        {
                            self.hitMouseCount = self.hitMouseCount - 1
                        }
                    }
                    self.currentScore_lab.text = "Reps:\(self.hitMouseCount)"

                    self.currentScore_lab.sizeToFit()
                    self.goal_Reps_lab.zc_x = self.currentScore_lab.zc_right + 5
                    self.goal_Reps_lab.zc_centerY = self.currentScore_lab.zc_centerY
            
                    self.ArmBool = false ; self.TriggerBool = false ;
                    
                    let numbers = UserDefaults.standard.object(forKey: GoalKey) as? NSNumber
                    let maxgoal = numbers?.intValue ?? 9999
                    
                    if UserDefaults.standard.object(forKey: ShowRepsUpAndDownKey) != nil
                    {
                        if "\(UserDefaults.standard.object(forKey: ShowRepsUpAndDownKey) ?? "")" == "up"
                        {
                            if self.hitMouseCount >= maxgoal
                            {                    // 分数到了
                                let alert = UIAlertController.init(title: "GOAL EXPIRED", message: "\(self.hitMouseCount) points, keep working", preferredStyle: .alert)
                                alert.addAction(UIAlertAction.init(title: "ok", style: .default, handler: nil))
                                self.present(alert, animated: true, completion: nil)
                                end_Games()
                            }
                        }
                        else
                        {
                            if self.hitMouseCount <= 0
                            {                    // 分数到了
                                let alert = UIAlertController.init(title: "GOAL EXPIRED", message: "\(self.hitMouseCount) points, keep working", preferredStyle: .alert)
                                alert.addAction(UIAlertAction.init(title: "ok", style: .default, handler: nil))
                                self.present(alert, animated: true, completion: nil)
                                end_Games()
                            }
                        }
                    }
                }
            }
            else
            {
                self.ArmBool = false ; self.TriggerBool = false ;
            } // 先打中trigger不算 - 重置
        }
    }
    
}

extension ViewController{
    
    @objc func armAndTriggerBtnClick(sender : UIButton) -> Void {
        if sender == self.arm_btn
        {
            UIView.animate(withDuration: TimeInterval.init(0.5), animations: {
                self.arm_imgV.transform = CGAffineTransform.init(rotationAngle: CGFloat(Double.pi*0.5))
            }) { (isbool) in
                self.arm_imgV.transform = CGAffineTransform.identity
            }
            
            let mouseItem : MouseItemView = self.itemsArray.firstObject as! MouseItemView
            mouseItem.hitMouseItem()
        }
        else
        {
            UIView.animate(withDuration: TimeInterval.init(0.5), animations: {
                self.trigger_imgV.transform = CGAffineTransform.init(rotationAngle: -CGFloat(Double.pi*0.5))
            }) { (isbool) in
                self.trigger_imgV.transform = CGAffineTransform.identity
            }
            
            let mouseItem : MouseItemView = self.itemsArray.lastObject as! MouseItemView
            mouseItem.hitMouseItem()
        }
    }
    
    func timerStart() -> Void {
        let speed : Double = UserDefaults.standard.object(forKey: "speed") as! Double
        self.myTimer = Timer.init(timeInterval: TimeInterval.init(5/speed), target: self, selector: #selector(timerActionForMouseOutHold), userInfo: nil, repeats: true)
        RunLoop.current.add(self.myTimer, forMode: .common)
    }
    
    func timerStop() -> Void {
        if self.myTimer.isValid
        {
            self.myTimer.invalidate()
        }
        let mouseItem : MouseItemView = self.itemsArray[_tempMouseIndex] as! MouseItemView
        mouseItem.mouseInHole()
    }// 暂停游戏
    
    @objc func timerActionForMouseOutHold() -> Void {
        self.TimerNum = self.TimerNum + 1
        
        if self.TimerNum%2 == 0
        {
            let mouseItem : MouseItemView = self.itemsArray.firstObject as! MouseItemView
            mouseItem.mouseInHole()

            let mouseItem1 : MouseItemView = self.itemsArray.lastObject as! MouseItemView
            mouseItem1.mouseOutHole()
        }// trigger
        else
        {
            let mouseItem : MouseItemView = self.itemsArray.firstObject as! MouseItemView
            mouseItem.mouseOutHole()
            
            let mouseItem1 : MouseItemView = self.itemsArray.lastObject as! MouseItemView
            mouseItem1.mouseInHole()
            self.ArmBool = false // 一轮结束后 重置 否则几轮后 击中trigger reps 也 + 1
        }// arm
        
        _tempMouseIndex = self.TimerNum%2
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.start_btn.currentTitle == "End"
        {
            self.timerStart()
            startGCDTimer()
        }
        print(UserDefaults.standard.object(forKey: TimeKey) ?? "",UserDefaults.standard.object(forKey: GoalKey) ?? "")
        let numbers1 = UserDefaults.standard.object(forKey: TimeKey) as? NSNumber
        self.goal_Time_lab.text = "/ \(transToHourMinSec(time: numbers1?.floatValue ?? 20 ))"
        self.goal_Reps_lab.text = "/ \(UserDefaults.standard.object(forKey: GoalKey) ?? "")"
        
        if UserDefaults.standard.object(forKey: ShowTimerUpAndDownKey) != nil
        {
            if "\(UserDefaults.standard.object(forKey: ShowTimerUpAndDownKey) ?? "")" == "up"
            {
                self.time_lab.text = "Time:00:00:00"
            }
            else
            {
                let numbers = UserDefaults.standard.object(forKey: TimeKey) as? NSNumber
                self.time_lab.text = "Time:\(transToHourMinSec(time: numbers?.floatValue ?? 0))"
            }
        }
        
        if UserDefaults.standard.object(forKey: ShowRepsUpAndDownKey) != nil
        {
            if UserDefaults.standard.object(forKey: GamingRepsKey) != nil
            {
                self.currentScore_lab.text = "Reps:\(UserDefaults.standard.object(forKey: GamingRepsKey) ?? "")"
            }
            else
            {
                if "\(UserDefaults.standard.object(forKey: ShowRepsUpAndDownKey) ?? "")" == "up"
                {
                    self.currentScore_lab.text = "Reps:0"
                }
                else
                {
                    self.currentScore_lab.text = "Reps:\(UserDefaults.standard.object(forKey: GoalKey) ?? "")"
                }
            }
        }
        
        if UserDefaults.standard.object(forKey: ShowTimerKey) != nil
        {
            if "\(UserDefaults.standard.object(forKey: ShowTimerKey) ?? "")" == "off"
            {
                self.time_lab.isHidden = true
                self.goal_Time_lab.isHidden = true
            }
            else
            {
                self.time_lab.isHidden = false
            }
        }
        
        if UserDefaults.standard.object(forKey: ShowTimerGoalKey) != nil
        {
            if "\(UserDefaults.standard.object(forKey: ShowTimerGoalKey) ?? "")" == "off"
            {
                self.goal_Time_lab.isHidden = true
            }
            else
            {
                self.goal_Time_lab.isHidden = false
                if self.time_lab.isHidden == false
                {
                    self.time_lab.sizeToFit()
                    self.goal_Time_lab.zc_x = self.time_lab.zc_right + 5
                    self.goal_Time_lab.text = "/ \(transToHourMinSec(time: numbers1?.floatValue ?? 0))"
                }
                else
                {
                    self.goal_Time_lab.isHidden = true
                }
            }
        }
        
        if UserDefaults.standard.object(forKey: ShowRepsKey) != nil
        {
            if "\(UserDefaults.standard.object(forKey: ShowRepsKey) ?? "")" == "off"
            {
                self.currentScore_lab.isHidden = true
                self.goal_Reps_lab.isHidden = true
            }
            else
            {
                self.currentScore_lab.isHidden = false
            }
        }
        
        if UserDefaults.standard.object(forKey: ShowRepsGoalKey) != nil
        {
            if "\(UserDefaults.standard.object(forKey: ShowRepsGoalKey) ?? "")" == "off"
            {
                self.goal_Reps_lab.isHidden = true
            }
            else
            {
                self.goal_Reps_lab.isHidden = false
                if self.currentScore_lab.isHidden == false
                {
                    self.currentScore_lab.sizeToFit()
                    self.goal_Reps_lab.zc_x = self.currentScore_lab.zc_right + 5
                    self.goal_Reps_lab.text = "/ \(UserDefaults.standard.object(forKey: GoalKey) ?? "")"
                }
                else
                {
                    self.goal_Reps_lab.isHidden = true
                }
            }
        }
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if self.start_btn.currentTitle == "End"
        {
            timerStop()
            codeTimer.suspend()
            UserDefaults.standard.set(self.hitMouseCount, forKey: GamingRepsKey)
            UserDefaults.standard.synchronize()
        }
        else
        {
            UserDefaults.standard.removeObject(forKey: GamingRepsKey)
            UserDefaults.standard.synchronize()
        }
    }
    
    // MARK: - 开始游戏
    @objc func startClick(sender : UIButton) -> Void {
        if sender.isSelected
        {
           end_Games()
        }
        else
        {
           start_Games()
        }
    }
    
    func start_Games() -> Void {
        let numbers = UserDefaults.standard.object(forKey: GoalKey) as? NSNumber
        let maxgoal = numbers?.intValue ?? 9999
        
        if UserDefaults.standard.object(forKey: ShowRepsUpAndDownKey) != nil
        {
            if "\(UserDefaults.standard.object(forKey: ShowRepsUpAndDownKey) ?? "")" == "up"
            {
                self.hitMouseCount = 0
            }
            else
            {
                self.hitMouseCount = maxgoal
            }
        }
        self.currentScore_lab.text = "Reps:\(self.hitMouseCount)"
        self.currentScore_lab.sizeToFit()
        self.goal_Reps_lab.zc_x = self.currentScore_lab.zc_right + 5
        self.goal_Reps_lab.zc_centerY = self.currentScore_lab.zc_centerY
        self.start_btn.isSelected = true
        self.timerStart()
        self.start_btn.setTitle("End", for: .normal)
        startGCDTimer()
    }
    
    func end_Games() -> Void {
        self.start_btn.isSelected = false
        timerStop()
        self.start_btn.setTitle("Start", for: .normal)
        codeTimer.suspend()
        hour = 0;min = 0;sec = 0;
        self.TimerNum = 0
        let mouseItem : MouseItemView = self.itemsArray.firstObject as! MouseItemView
        mouseItem.mouseInHole()
        let mouseItem1 : MouseItemView = self.itemsArray.lastObject as! MouseItemView
        mouseItem1.mouseInHole()
    }
    
    @objc func settingClick() -> Void {
        let vc = SettingViewController.init()
        vc.isplayer = self.hitSound.isPlaying()
        vc.modalPresentationStyle = .fullScreen
        self.present(vc, animated: true, completion: nil)
    } // push setting
    
    @objc func goalTimerClick() -> Void {
        let vc = GoalAndTimerViewController.init()
        vc.modalPresentationStyle = .fullScreen
        self.present(vc, animated: true, completion: nil)
    } // push setting
    
    fileprivate func startGCDTimer() {
        // 设定这个时间源是每秒循环一次，立即开始
        codeTimer.schedule(deadline: .now(), repeating: .seconds(1))
        // 设定时间源的触发事件
        codeTimer.setEventHandler(handler: {
            
            // 返回主线程处理一些事件，更新UI等等
            DispatchQueue.main.async {
                self.timerMethod()
            }
        })
        
        // 判断是否取消，如果已经取消了，调用resume()方法时就会崩溃！！！
        if codeTimer.isCancelled {
            return
        }
        // 启动时间源
        codeTimer.resume()
    }
    
    @objc fileprivate func timerMethod() {
        if sec >= 59
        {
            sec = 0
            if min >= 59{ min = 0; hour = hour + 1 }
            else { min = min + 1 }
        }
        else
        {
            sec = sec + 1
        }
        
        let sumSec = hour * 3600 + min * 60 + sec
        let numbers = UserDefaults.standard.object(forKey: TimeKey) as? NSNumber
        let maxTime = numbers?.intValue ?? 9999
        
        if UserDefaults.standard.object(forKey: ShowTimerUpAndDownKey) != nil
        {
            if "\(UserDefaults.standard.object(forKey: ShowTimerUpAndDownKey) ?? "")" == "up"
            {
                self.time_lab.text = "Time : " + String(format: "%02d", hour) + ":" + String(format: "%02d", min) + ":" + String(format: "%02d", sec)
            }
            else
            {
                let currenttimers = maxTime - sumSec
                self.time_lab.text = "Time:\(transToHourMinSec(time: Float(currenttimers)))"
            }
        }
        
        self.time_lab.sizeToFit()
        self.goal_Time_lab.zc_x = self.time_lab.zc_right + 5
        self.goal_Time_lab.zc_centerY = self.time_lab.zc_centerY
        
        if UserDefaults.standard.object(forKey: TimeKey) != nil
        {
            
            if UserDefaults.standard.object(forKey: ShowTimerUpAndDownKey) != nil
            {
                if "\(UserDefaults.standard.object(forKey: ShowTimerUpAndDownKey) ?? "")" == "up"
                {
                    if sumSec >= maxTime
                    {
                        // 到时间了
                        let alert = UIAlertController.init(title: "TIMER EXPIRED", message: "Your \(String(format: "%02d", hour) + ":" + String(format: "%02d", min) + ":" + String(format: "%02d", sec)) timer has ran out!", preferredStyle: .alert)
                        alert.addAction(UIAlertAction.init(title: "ok", style: .default, handler: nil))
                        self.present(alert, animated: true, completion: nil)
                        end_Games()
                    }
                }
                else
                {
                    let currenttimers = maxTime - sumSec
                    if currenttimers <= 0
                    {
                        // 到时间了
                        let alert = UIAlertController.init(title: "TIMER EXPIRED", message: "Your \(String(format: "%02d", hour) + ":" + String(format: "%02d", min) + ":" + String(format: "%02d", sec)) timer has ran out!", preferredStyle: .alert)
                        alert.addAction(UIAlertAction.init(title: "ok", style: .default, handler: nil))
                        self.present(alert, animated: true, completion: nil)
                        end_Games()
                    }
                }
            }
           
        }
        
    }
    
    // MARK: - initUI
    func initUI() -> Void {
        setMouseViewItems()
        
        if UserDefaults.standard.object(forKey: ShowTimerKey) == nil
        {
            UserDefaults.standard.set("on", forKey: ShowTimerKey)
        }
        if UserDefaults.standard.object(forKey: ShowTimerGoalKey) == nil
        {
            UserDefaults.standard.set("on", forKey: ShowTimerGoalKey)
        }
        if UserDefaults.standard.object(forKey: ShowRepsKey) == nil
        {
            UserDefaults.standard.set("on", forKey: ShowRepsKey)
        }
        if UserDefaults.standard.object(forKey: ShowRepsGoalKey) == nil
        {
            UserDefaults.standard.set("on", forKey: ShowRepsGoalKey)
        }
        if UserDefaults.standard.object(forKey: ShowRepsUpAndDownKey) == nil
        {
            UserDefaults.standard.set("up", forKey: ShowRepsUpAndDownKey)
        }
        if UserDefaults.standard.object(forKey: ShowTimerUpAndDownKey) == nil
        {
            UserDefaults.standard.set("up", forKey: ShowTimerUpAndDownKey)
        }
        if UserDefaults.standard.object(forKey: SoundIsPlayKey) == nil
        {
           UserDefaults.standard.set("false", forKey: SoundIsPlayKey)
        }
        UserDefaults.standard.synchronize()
        
        NotificationCenter.default.addObserver(self, selector: #selector(setupSound_On), name: NSNotification.Name(rawValue: NotifictionKey_Sound_Play), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(setupSound_Off), name: NSNotification.Name(rawValue: NotifictionKey_Sound_Pause), object: nil)
    }
    
    @objc func setupSound_On() -> Void {
        self.hitSound.playSound()
    }
    
    @objc func setupSound_Off() -> Void {
        self.hitSound.pauseSound()
    }
    
    func setMouseViewItems() -> Void {
      
        view.addSubview(self.bg_imgV)
        view.addSubview(self.start_btn)
        view.addSubview(self.currentScore_lab)
        view.addSubview(self.goal_Reps_lab)
        view.addSubview(self.goal_Time_lab)
        view.addSubview(self.time_lab)
        view.addSubview(self.setting_btn)
        view.addSubview(self.goal_Timer_btn)
        self.itemsArray.add(self.itemView)
        view.addSubview(self.itemView)
        self.itemsArray.add(self.itemView2)
        view.addSubview(self.itemView2)
        view.addSubview(self.arm_btn)
        view.addSubview(self.trigger_btn)
        view.addSubview(self.arm_imgV)
        view.addSubview(self.trigger_imgV)
        
        self.currentScore_lab.sizeToFit()
        self.goal_Reps_lab.zc_x = self.currentScore_lab.zc_right + 5
        self.goal_Reps_lab.zc_centerY = self.currentScore_lab.zc_centerY
        self.time_lab.sizeToFit()
        self.goal_Time_lab.zc_x = self.time_lab.zc_right + 5
        self.goal_Time_lab.zc_centerY = self.time_lab.zc_centerY
    }
    
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
            
            if ScreenWidth != size.width
            {
                ScreenWidth  = size.width
                ScreenHeight = size.height
                Y_MouseItem  = ScreenHeight/2 - (ScreenWidth - 40)/6
                W_MouseItem  = (ScreenWidth - 40)/3
            }
            print("W_MouseItem + \(W_MouseItem)")
            self.setting_btn.frame  = CGRect.init(x: ScreenWidth - 100, y: 50, width: 80, height: 40)
            self.goal_Timer_btn.frame = CGRect.init(x: ScreenWidth - 100, y: 80, width: 80, height: 40)
            self.bg_imgV.frame      = CGRect.init(x: 50, y: Y_MouseItem, width: ScreenWidth-100, height: 300)
            self.start_btn.frame    = CGRect.init(x: ScreenWidth/2 - 100, y: ScreenHeight - 100, width: 200, height: 50)
            self.itemView.frame     = CGRect.init(x: ScreenWidth/2 - W_MouseItem - 10, y: Y_MouseItem, width: W_MouseItem, height: W_MouseItem)
            self.itemView2.frame    = CGRect.init(x: ScreenWidth/2 + 10, y: Y_MouseItem, width: W_MouseItem, height: W_MouseItem)
            self.arm_btn.frame      = CGRect.init(x: 10, y: Y_MouseItem, width: 80, height: 30);
            self.trigger_btn.frame  = CGRect.init(x: ScreenWidth - 10 - 80, y: Y_MouseItem, width: 80, height: 30);
            self.arm_imgV.frame     = CGRect.init(x: self.itemView.zc_x, y: self.itemView.zc_y - 64, width: 128, height: 128)
            self.trigger_imgV.frame = CGRect.init(x: self.itemView2.zc_x + self.itemView2.zc_width - 128, y: self.itemView2.zc_y - 64, width: 128, height: 128)
            
            self.itemView.refreshUI()
            self.itemView2.refreshUI()
        }
    }
}

func transToHourMinSec(time: Float) -> String
{
    let allTime: Int = Int(time)
    var hours = 0
    var minutes = 0
    var seconds = 0
    var hoursText = ""
    var minutesText = ""
    var secondsText = ""
    
    hours = allTime / 3600
    hoursText = hours > 9 ? "\(hours)" : "0\(hours)"
    
    minutes = allTime % 3600 / 60
    minutesText = minutes > 9 ? "\(minutes)" : "0\(minutes)"
    
    seconds = allTime % 3600 % 60
    secondsText = seconds > 9 ? "\(seconds)" : "0\(seconds)"
    
    return "\(hoursText):\(minutesText):\(secondsText)"
}// 秒转时间

// MARK: - 增加是否在当前显示的窗口
extension UIView {
    
    public func isShowingnKeyWindow() -> Bool {
        
        guard let keyWindow = UIApplication.shared.keyWindow else {return false}
        //以主窗口的左上角为原点, 计算self的矩形框(谁调用这个方法这个self就是谁)
        let frame = keyWindow.convert(self.frame, from: self.superview)
        
        //判断主窗口的bounds和self的范围是否有重叠
        let isIntersects = frame.intersects(keyWindow.bounds)
        return isIntersects && !self.isHidden && self.alpha > 0 && self.window == keyWindow
    }
}

extension UIView {
    
    var zc_x: CGFloat {
        get {
            return frame.origin.x
        }
        set{
            var tempFrame: CGRect = frame
            tempFrame.origin.x = newValue
            frame = tempFrame
        }
    }
    
    var zc_y: CGFloat {
        set {
            var tempFrame: CGRect = frame
            tempFrame.origin.y = newValue
            frame = tempFrame
        }
        get {
            return frame.origin.y
        }
    }
    
    var zc_height : CGFloat {
        get {
            return frame.size.height
        }
        set(newVal) {
            var tmpFrame : CGRect = frame
            tmpFrame.size.height  = newVal
            frame                 = tmpFrame
        }
    }
    
    var zc_width : CGFloat {
        get {
            return frame.size.width
        }
        set(newVal) {
            var tmpFrame : CGRect = frame
            tmpFrame.size.width   = newVal
            frame                 = tmpFrame
        }
    }
    
    var zc_left : CGFloat {
        get {
            return zc_x
        }
        set(newVal) {
            zc_x = newVal
        }
    }
    
    var zc_right : CGFloat {
        get {
            return zc_x + zc_width
        }
        set(newVal) {
            zc_x = newVal - zc_width
        }
    }
    
    var zc_bottom : CGFloat {
        get {
            return zc_y + zc_height
        }
        set(newVal) {
            zc_y = newVal - zc_height
        }
    }
    
    var zc_center: CGPoint {
        
        get {
            return CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0)
        }
        set {
            center = CGPoint(x: newValue.x, y: newValue.y)
        }
    }
    
    var zc_centerX : CGFloat {
        get {
            return center.x
        }
        set(newVal) {
            center = CGPoint(x: newVal, y: center.y)
        }
    }

    var zc_centerY : CGFloat {
        get {
            return center.y
        }
        set(newVal) {
            center = CGPoint(x: center.x, y: newVal)
        }
    }
}

